var angular = require('angular');
var coreRoutes = require('./routes/base.routes');
var navMenuService = require('./services/menu.service');
var navbarController = require('./components/navbar/navbar.controller');
var navbarComponent = require('./components/navbar/navbar');

var defaultController = require('./controllers/default.controller');

var appContext = require('../../config/app.context');

const moduleName = 'core';

angular.module(moduleName, [])
    .config(coreRoutes)
    .factory('navMenuService', navMenuService)
    .component('navbar', navbarComponent)
    .controller('navbarController', navbarController)
    .controller('defaultController',defaultController)
    .run(run);

run.$inject = [
    '$location',
    '$rootScope',
    '$http'
];

function run($location, $rootScope, $http) {
    // $transitions.onStart({}, function(transition) {
    //     var url = transition.router.urlRouter.location;
    //     console.log(transition.router.urlRouter.location);
    // });

    if (!$rootScope.globalData) {
        $rootScope.globalData = {};
    }

    $rootScope.globalData.contextPath = appContext.path;

    $rootScope.$on('$locationChangeStart', function(event, current, previous) {
        console.log("location changed to: " + JSON.stringify(current));

        $rootScope.globalData.canSearch = $location.path().indexOf(appContext.path + '/restaurant/') != -1;

        $http.get(appContext.path + '/api/customers/isLogin').then(
            function(response) {
                $rootScope.globalData.loginedCustomer = response.data.customerInfo;
                $rootScope.$broadcast('loginedCustomer');
                if (!response.data.customerInfo) {
                    redirectToLogin(current);
                }
            },
            function(err) {
                redirectToLogin(current);
            }
        );

        function redirectToLogin(url) {
            if (url.split('/').indexOf('auth') != -1) {
                console.log('auth triggered');
                
                // validate if user logined
                $location.path(appContext.path + '/login');
            }
        }

    });
}

module.exports = moduleName;